package com.example.demo.router;

import com.example.demo.base.BaseControl;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author masc
 * @date 2022-09-07 16:18
 * <p></p>
 */
@Component
public class MyStrategyRoute {
    @Resource
    private ApplicationContext applicationContext;
    private Map<Integer, BaseControl> beansMap = new HashMap<>(); //容器启动的时候，把bean放到Map中
    private Optional<BaseControl> defaultBeans;

    @PostConstruct
    public void postConstruct() {
        Map<String, BaseControl> map = applicationContext.getBeansOfType(BaseControl.class); // 获取容器中的实列（对象）
        if (map != null) {
            beansMap = map.values().stream().collect(Collectors.toMap(BaseControl::getVariantFormId, Function.identity(), (k1, k2) -> k1));
            defaultBeans = map.values().stream().findFirst();
        }
    }

    public Optional<BaseControl> getVariantControl(Integer variantFormId) {
        return Optional.ofNullable(beansMap.get(variantFormId));
    }

    public Optional<BaseControl> getDefaultVariantControl() {
        return defaultBeans;
    }
}
